package com.example.my_bookkeeping.data.manager;

import com.example.my_bookkeeping.data.user.BookKeep;
import com.example.my_bookkeeping.data.user.User;

import java.util.ArrayList;

public class BookKeepManager extends Manager {
    // 使用单例设计模式，在本类中对记账数据进行管理
    private static final BookKeepManager instance = new BookKeepManager();
    private final UserManager userManager = UserManager.getInstance();

    private BookKeepManager() {}
    public static BookKeepManager getInstance() {
        return instance;
    }

    public ArrayList<BookKeep> getAll() {
        User currentUser = userManager.getCurrentUser();
        if (currentUser!= null)
            return currentUser.getAllBookKeeps();
        return new ArrayList<>();
    }

    public void add(String time, double amount, String category, String remark, boolean isIncome) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser != null) {
            currentUser.addBookKeep(time, amount, category, remark, isIncome);
        }
        notifyObservers();
    }

    public void delete(BookKeep bookKeep) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser!= null) {
            currentUser.deleteBookKeep(bookKeep);
        }
        notifyObservers();
    }

    // 更新一个记账信息（接收字段参数）
    public void update(long id, double amount, String category, String remark) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser!= null) {
            currentUser.updateBookKeepFields(id, amount, category, remark);
        }
        notifyObservers();
    }

    public interface SearchBookKeepBy {
        boolean isMatch(BookKeep bookKeep);
    }

    public ArrayList<BookKeep> searchBookKeep(SearchBookKeepBy searchBookKeepBy) {
        User currentUser = userManager.getCurrentUser();
        if (currentUser == null)
            return new ArrayList<>();
        ArrayList<BookKeep> bookKeeps = currentUser.getAllBookKeeps();
        ArrayList<BookKeep> result = new ArrayList<>();
        for (BookKeep bookKeep : bookKeeps) {
            if (searchBookKeepBy.isMatch(bookKeep))
                result.add(bookKeep);
        }
        return result;
    }
}
